const express = require('express')
const Router = express.Router
const router = new Router()
const wechat = require('../wx/wechat.js')
const auth = require('../wx/auth_.js')
const sha1 = require('sha1')
const {url,appID} = require('../config')

router.get('/',async(req,res)=>{
  // 检测授权重定向后 获取 openid access_token
    if(req.query && req.query.code){
      console.log(req.query)
      try {
        await wechat.fetchOpenId(req.query.code)
        res.redirect('http://localhost:8000/index')
      } catch (error) {
        console.log(error,'获取网页access_token出错>>>>>>')
        res.redirect('login')
      }
    }else{
      res.redirect('login')
    }
})

//获取用户授权
router.get('/auth',async(req,res)=>{
  try {
    await wechat.fetchOpenId()
    res.redirect('index')
  } catch (error) {
    console.log(error,'用户未授权')
    // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdb56ba0c227e8be2&redirect_uri=http://d6eefd4f.ngrok.io&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    let redirectUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    res.redirect(redirectUrl)
  }
})


//获取用户信息 需先授权
router.get('/userinfo',async(req,res)=>{
  try {
    let data = await wechat.getUserInfo()
    res.send(data)
  } catch (error) {
    res.send({code:10001,errorMsg:'用户未登入'})
  }
})


router.get('/login',(req,res)=>{
  res.render('login')
})

router.get('/logout',(req,res)=>{
  res.redirect('login')
})

router.get('/index',(req,res)=>{
    res.render('index');
})

router.get('/movie',(req,res)=>{
    res.render('movie');
})

router.get('/search', async(req,res) => {
    /*
    生成js-sdk使用的签名：
      1. 组合参与签名的四个参数：jsapi_ticket（临时票据）、noncestr（随机字符串）、timestamp（时间戳）、url（当前服务器地址）
      2. 将其进行字典序排序，以'&'拼接在一起
      3. 进行sha1加密，最终生成signature
   */
  const noncestr = Math.random().toString().split('.')[0]
  const timestamp = Date.now()
  const {ticket} = await wechat.fetchTicket()
  let arr = [
    `jsapi_ticket=${ticket}`,
    `noncestr=${noncestr}`,
    `timestamp=${timestamp}`,
    `url=${url}/search`
  ]
  let signature = sha1(arr.sort().join('&'))
  console.log(signature,'生成签名 >>>>>')
  //渲染页面 返回 签名参数
  res.render('search', {
    signature,
    noncestr,
    timestamp
  });
})

router.use(auth())
module.exports = router
